package products;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import core.EmailUtil;
import core.MD5Util;
import core.SendSms;
import code.Code;
import dao.Codevalue;
import dao.CodevalueDAO;
import dao.Complaints;
import dao.ComplaintsDAO;
import dao.GameTab;
import dao.GameTabDAO;
import dao.Productsnews;
import dao.ProductsnewsDAO;
import dao.Questionandanswer;
import dao.QuestionandanswerDAO;
import dao.RoleTab;
import dao.RoleTabDAO;
import dao.ServerTab;
import dao.ServerTabDAO;
import dao.Serverinfo;
import dao.ServerinfoDAO;
import dao.UserTab;
import dao.UserTabDAO;
import server.UserServer;
import viewModel.IndesGameNewsView;
import viewModel.PasswordBack;
import viewModel.Root;
import viewModel.SecretQuestion;
import viewModel.UserSecurityInfo;

@org.springframework.stereotype.Controller
public class Controller {
	private static final Logger logger = Logger.getLogger(Controller.class);
	@Autowired
	private UserServer userServer;
	@Autowired
	private UserTabDAO userTabDAO;
	@Autowired
	private ServerTabDAO serverTabDAO;
	@Autowired
	private CodevalueDAO codevalueDAO;
	@Autowired
	private ServletContext servletContext;
	@Autowired
	private GameTabDAO gameTabDAO;
	@Autowired
	private ProductsnewsDAO productsnewsDAO;
	@Autowired
	private QuestionandanswerDAO questionandanswerDAO;
	@Autowired
	private ComplaintsDAO complaintsDAO;
	@Autowired
	private ServerinfoDAO serverinfoDAO;
	@Autowired
	private RoleTabDAO  roleTabDAO;

	/**
	 * 首页
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { " ", "/", "/index" })
	public String index(ModelMap map, HttpServletRequest request) {
		try {
			String path = request.getContextPath();
			map.put("path", request.getContextPath());
			map.put("basePath",
					request.getScheme() + "://" + request.getServerName() + ":"
							+ request.getServerPort() + path + "/");
			ArrayList<GameTab> games = (ArrayList<GameTab>) gameTabDAO
					.findAll();
			map.put("games", games);
			ArrayList<IndesGameNewsView> gameNews = new ArrayList<>();
			ArrayList<IndesGameNewsView> productsNews = new ArrayList<>();
			for (GameTab gameTab : games) {
				Productsnews example = new Productsnews();
				IndesGameNewsView temp = new IndesGameNewsView();
				temp.setGameTab(gameTab);
				example.setGameId(gameTab.getGameId());
				example.setInfoType(Code.GameNews);
				ArrayList<Productsnews> news = (ArrayList<Productsnews>) productsnewsDAO
						.findByExample(example);
				temp.setArrayList(news);
				gameNews.add(temp);
				temp.setNum(news.size());
			}
			ArrayList<Productsnews> newsProducts = (ArrayList<Productsnews>) productsnewsDAO
					.findByInfoType(Code.ProductNews);
			map.put("gameNews", gameNews);
			map.put("productsNews", newsProducts);
			map.put("title", "首页");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "index";
	}

	@RequestMapping("/login")
	public String login(String backurl, ModelMap map, String showPage) {
		try {
			if (backurl != null && backurl.indexOf("loginout") == -1) {
				if (showPage != null) {
					backurl = backurl + "&showPage=" + showPage;
				}
				map.put("backurl", backurl);
			} else {
				map.put("backurl", "/products/index");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "login";
	}

	/**
	 * 登录校验密码与验证码
	 * 
	 * @param acc
	 * @param pwd
	 * @param vCode
	 * @param session
	 * @return
	 */
	@RequestMapping("/checkpwd")
	@ResponseBody
	public String checkPwd(String acc, String pwd, String vCode,
			HttpSession session) {
		String flag = null;
		try {
			String vCodeServer = (String) session
					.getAttribute("randomCodeLogin");
			if (vCodeServer != null) {
				if (!vCodeServer.toLowerCase().equals(vCode.toLowerCase())) {
					return "codeError";
				}
			}
			UserTab userTab = new UserTab();
			userTab.setUserAcc(acc);
			userTab.setPwdPho(pwd);
			flag = userServer.check(acc, pwd, session);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if ("success".equals(flag)) {
			session.setAttribute("name", acc);
			return "success";
		} else if ("freeze".equals(flag)) {
			return "freeze";
		} else {
			return "error";
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/createVCode")
	public void createVCode(HttpServletRequest request,
			HttpServletResponse response, String codeType) {

		try {
			// 设置验证图片的宽度, 高度, 验证码的个数
			int width = 80;
			int height = 30;
			int codeCount = 4;

			// 验证码字体的高度
			int fontHeight = 4;

			// 验证码中的单个字符基线. 即：验证码中的单个字符位于验证码图形左上角的 (codeX, codeY) 位置处
			int codeX = 0;
			int codeY = 0;

			// 验证码由哪些字符组成
			char[] codeSequence = "ABCDEFGHKMNOPQRSTUVWXYZabcdefghkmnopqrstuvwxyz23456789"
					.toCharArray();

			// 初始化验证码图形属性
			fontHeight = height - 2;
			codeX = width / (codeCount + 2);
			codeY = height - 4;

			// 定义一个类型为 BufferedImage.TYPE_INT_BGR 类型的图像缓存
			BufferedImage buffImg = null;
			buffImg = new BufferedImage(width, height,
					BufferedImage.TYPE_3BYTE_BGR);

			// 在 buffImg 中创建一个 Graphics2D 图像
			Graphics2D graphics = null;
			graphics = buffImg.createGraphics();

			// 设置一个颜色, 使 Graphics2D 对象的后续图形使用这个颜色
			graphics.setColor(Color.WHITE);

			// 填充一个指定的矩形: x - 要填充矩形的 x 坐标; y - 要填充矩形的 y 坐标; width - 要填充矩形的宽度;
			// height
			// - 要填充矩形的高度
			graphics.fillRect(0, 0, width, height);

			// 创建一个 Font 对象: name - 字体名称; style - Font 的样式常量; size - Font 的点大小
			Font font = null;
			font = new Font("", Font.BOLD, fontHeight);
			// 使 Graphics2D 对象的后续图形使用此字体
			graphics.setFont(font);

			graphics.setColor(Color.BLACK);

			// 绘制指定矩形的边框, 绘制出的矩形将比构件宽一个也高一个像素
			graphics.drawRect(0, 0, width - 1, height - 1);

			// 随机产生 15 条干扰线, 使图像中的认证码不易被其它程序探测到
			Random random = null;
			random = new Random();
			graphics.setColor(Color.GREEN);
			for (int i = 0; i < 20; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int x1 = random.nextInt(20);
				int y1 = random.nextInt(20);
				graphics.drawLine(x, y, x + x1, y + y1);
			}

			// 创建 randomCode 对象, 用于保存随机产生的验证码, 以便用户登录后进行验证
			StringBuffer randomCode;
			randomCode = new StringBuffer();

			for (int i = 0; i < codeCount; i++) {
				// 得到随机产生的验证码数字
				String strRand = null;
				strRand = String.valueOf(codeSequence[random.nextInt(53)]);

				// 用随机产生的颜色将验证码绘制到图像中
				graphics.setColor(Color.BLUE);
				graphics.drawString(strRand, (i + 1) * codeX, codeY);
				randomCode.append(strRand);
			}
			if ("randomCodeLogin".equals(codeType)) {
				request.getSession().setAttribute("randomCodeLogin",
						randomCode.toString());
			}
			if ("randomCodePasswordBack".equals(codeType)) {
				request.getSession().setAttribute("randomCodePasswordBack",
						randomCode.toString());
			}

			// 禁止图像缓存
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);

			// 将图像输出到输出流中
			ServletOutputStream sos = null;
			sos = response.getOutputStream();
			ImageIO.write(buffImg, "jpeg", sos);
			sos.close();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	/**
	 * 注册页面
	 * 
	 * @param m
	 * @param map
	 * @return
	 */
	@RequestMapping("/regist")
	public String regist(String m, ModelMap map) {
		try {
			if ("toregphone".equals(m)) {
				map.put("registerType", Code.RegisterTypePhone);
				map.put("tipsParam", "phone");
				map.put("regParam", "mobile");
				map.put("calibrationUrl", "regcheckphone");
				map.put("ajaxParam", "phone");
			} else if ("toregemail".equals(m)) {
				map.put("registerType", Code.RegisterTypeEmail);
				map.put("regParam", "email");
				map.put("ajaxParam", "name");
				map.put("tipsParam", "email");
				map.put("calibrationUrl", "regcheckname");
			} else if ("toregnickname".equals(m)) {
				map.put("registerType", Code.RegisterTypeNormal);
				map.put("calibrationUrl", "regcheckname");
				map.put("regParam", "username");
				map.put("ajaxParam", "name");
				map.put("tipsParam", "account");
			} else {
				map.put("registerType", Code.RegisterTypePhone);
				map.put("tipsParam", "phone");
				map.put("regParam", "mobile");
				map.put("calibrationUrl", "regcheckphone");
				map.put("ajaxParam", "phone");
			}
			map.put("m", m);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "regist";
	}

	/**
	 * 校验验证码
	 * 
	 * @param code
	 * @param session
	 * @return
	 */
	@RequestMapping("/checkVCode")
	@ResponseBody
	public String checkVCode(String code, HttpSession session, String codeType) {
		try {
			if (code != null) {
				String vCodeServer = null;
				if ("randomCodeLogin".equals(codeType)) {
					vCodeServer = (String) session
							.getAttribute("randomCodeLogin");
				}
				if ("passwordBack".equals(codeType)) {
					vCodeServer = (String) session
							.getAttribute("randomCodePasswordBack");
				}
				if (vCodeServer != null) {
					return code.toLowerCase().equals(vCodeServer.toLowerCase()) ? "1"
							: "-1";
				} else {
					return Code.Success;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return Code.Error;
	}

	/**
	 * 校验用户名是否存在,-1表示存在,1表示不存在
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping("/regcheckname")
	@ResponseBody
	public String regcheckname(String name) {
		return userServer.regcheckname(name);
	}

	/**
	 * 校验身份证
	 * 
	 * @param idcard
	 * @return
	 */
	@RequestMapping("/checkIdCard")
	@ResponseBody
	public String checkIdCard(String idcard) {
		return userServer.checkIdCard(idcard);
	}

	@RequestMapping("/email")
	@ResponseBody
	public String checkEmail(String email) {
		return userServer.checkEmail(email);
	}

	/**
	 * 提交注册信息
	 * 
	 * @param securityInfo
	 * @param registerType
	 * @param map
	 * @return
	 */
	@RequestMapping("/acc")
	public String acc(UserSecurityInfo securityInfo, String registerType,
			ModelMap map, HttpServletRequest request) {
		try {
			if (Code.RegisterTypeNormalStr.equals(registerType)) {
				securityInfo.setAccountStatus((short) 1);
				securityInfo.setSecurityLv((short) 1);
				userServer.acc(securityInfo);
				map.put("accountName", securityInfo.getUseraccount());
				map.put("securityLv", Code.LowSecurityLv);
			} else if (Code.RegisterTypePhoneStr.equals(registerType)) {
				securityInfo.setAccountStatus((short) 1);
				securityInfo.setSecurityLv((short) 1);
				securityInfo.setPhone(securityInfo.getUseraccount());
				userServer.acc(securityInfo);
				map.put("accountName", securityInfo.getUseraccount());
				map.put("securityLv", Code.LowSecurityLv);
			} else if (Code.RegisterTypeEmailStr.equals(registerType)) {
				String path = request.getContextPath();
				String basePath = request.getScheme() + "://"
						+ request.getServerName() + ":"
						+ request.getServerPort() + path + "/";

				map.put("emailServer",
						securityInfo.getUseraccount().split("\\.")[0]
								.split("@")[1]);
				map.put("secondStep", securityInfo.getUseraccount());
				EmailUtil eUtil = new EmailUtil();
				String emailUrl = MD5Util.getMd5(String.valueOf(new Date()
						.getTime()));
				eUtil.sendEmail(serverinfoDAO, securityInfo.getUseraccount(),
						"乐控科技账号激活的确认邮件", "<a href='" + basePath
								+ "registeremailurl?code=" + emailUrl + "'/>"
								+ basePath + "registeremailurl?code="
								+ emailUrl + "</a>", "点击链接激活乐控科技账号");
				securityInfo.setAccountStatus((short) 0);
				securityInfo.setSecurityLv((short) 1);
				securityInfo.setEmailUrl(emailUrl);
				userServer.acc(securityInfo);
				map.put("registerType", Code.RegisterTypeEmail);
				map.put("calibrationUrl", "regcheckname");
				map.put("regParam", "email");
				map.put("ajaxParam", "email");
				map.put("tipsParam", "email");
				return "regist";
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "registSuccess";
	}

	@RequestMapping("/userSafeindex")
	public String userSafeindex() {
		return "userSafeindex";
	}

	@RequestMapping("/userIndex")
	public String userIndex() {
		return "userIndex";
	}

	/**
	 * 用户协议
	 * 
	 * @return
	 */
	@RequestMapping("/rules")
	public String rules() {
		return "rules";
	}

	/**
	 * 重发邮件
	 * 
	 * @param email
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/resendregemail")
	public String resendregemail(String email, HttpServletRequest request) {
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ path + "/";
			UserTab userTab = userTabDAO.findByUserAcc(email).get(0);
			EmailUtil eUtil = new EmailUtil();
			String emailUrl = userTab.getEmailUrl();
			eUtil.sendEmail(serverinfoDAO, email, "乐控科技账号激活的确认邮件", "<a href='"
					+ basePath + "registeremailurl?code=" + emailUrl + "'/>"
					+ basePath + "registeremailurl?code=" + emailUrl + "</a>",
					"点击链接激活乐控科技账号");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "1";
	}

	@RequestMapping("/registeremailurl")
	public String registerEmailUrl(String code) {
		try {
			UserTab userTab = (UserTab) userTabDAO.findByEmailUrl(code).get(0);
			if (userTab != null) {
				userTab.setAccountStatus((short) 1);
				userTabDAO.attachDirty(userTab);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "registSuccess";
	}

	/**
	 * 注销
	 * 
	 * @param session
	 */
	@RequestMapping("/loginout")
	public String loginout(HttpSession session, String currenturl,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap map) {
		try {
			session.invalidate();
			ArrayList<GameTab> games = (ArrayList<GameTab>) gameTabDAO
					.findAll();
			map.put("games", games);
			ArrayList<IndesGameNewsView> gameNews = new ArrayList<>();
			ArrayList<IndesGameNewsView> productsNews = new ArrayList<>();
			for (GameTab gameTab : games) {
				Productsnews example = new Productsnews();
				IndesGameNewsView temp = new IndesGameNewsView();
				temp.setGameTab(gameTab);
				example.setGameId(gameTab.getGameId());
				example.setInfoType(Code.GameNews);
				ArrayList<Productsnews> news = (ArrayList<Productsnews>) productsnewsDAO
						.findByExample(example);
				temp.setArrayList(news);
				gameNews.add(temp);
				temp.setNum(news.size());
			}
			ArrayList<Productsnews> newsProducts = (ArrayList<Productsnews>) productsnewsDAO
					.findByInfoType(Code.ProductNews);
			map.put("gameNews", gameNews);
			map.put("productsNews", newsProducts);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "/index";
	}

	/**
	 * 个人信息 描述： 创建人： xiaoy 创建时间：2015年2月26日 下午5:58:44 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/personalcenter")
	public String personalCenter(HttpSession session, ModelMap map) {
		try {
			UserTab userTab = userTabDAO.findByUserAcc(
					session.getAttribute("name")).get(0);
			ArrayList<Codevalue> codevalues = (ArrayList<Codevalue>) codevalueDAO
					.findAll();
			map.put("user", userTab);
			map.put("codeValues", codevalues);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		map.put("title", "个人中心");
		return "personalCenter";
	}

	@RequestMapping("/secretEmailForm")
	@ResponseBody
	public String secretEmailForm(HttpSession session, ModelMap map,
			HttpServletRequest request, String secretEmail) {
		String email = request.getParameter("secretEmail");
		try {
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ path + "/";
			String account = (String) session.getAttribute("name");
			EmailUtil eUtil = new EmailUtil();
			String emailUrl = MD5Util.getMd5(UUID.randomUUID().toString());
			eUtil.sendEmail(serverinfoDAO, email, "乐控科技账号密保邮箱激活的确认邮件",
					"<a href='" + basePath + "secretemailurl?code=" + emailUrl
							+ "&email=" + email + "'/>" + basePath
							+ "secretemailurl?code=" + emailUrl + "</a>",
					"点击链接激活密保邮箱");
			userServer.secretEmailForm(account, emailUrl);
			if (email.split("\\.").length < 1) {
				return null;
			}
			if (email.split("\\.")[0].split("@").length < 2) {
				return null;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return email.split("\\.")[0].split("@")[1];
	}

	@RequestMapping("/secretemailurl")
	public String secretemailurl(String code, String email) {
		return userServer.secretemailurl(email, code);
	}

	@RequestMapping("/secretQuestionForm")
	@ResponseBody
	public String secretQuestionForm(SecretQuestion question,
			HttpSession session) {
		try {
			userServer.secretQuestionForm(question,
					(String) session.getAttribute("name"));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	/**
	 * 描述： 修改昵称 创建人： xiaoy 创建时间：2015年2月27日 下午7:16:38 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/modifyNickname")
	@ResponseBody
	public void modifyNickname(HttpSession session, String nickname) {
		try {
			userServer.modifyNickname(session, nickname);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	/**
	 * 描述： 校验旧密码 创建人： xiaoy 创建时间：2015年2月28日 上午10:43:00 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/checkoldpwd")
	@ResponseBody
	public String checkOldPwd(HttpSession session, String oldPwd) {
		String flag = null;
		try {
			String accName = session.getAttribute("name").toString();
			flag = userServer.check(accName, oldPwd, session);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if ("error".equals(flag)) {
			return "error";
		}
		return "success";
	}

	/**
	 * 描述： 设置新密码 创建人： xiaoy 创建时间：2015年2月28日 上午10:42:52 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/setnewpwd")
	@ResponseBody
	public String setNewPwd(HttpSession session, String newPwd) {
		try {
			userServer.setNewPwd(session.getAttribute("name").toString(),
					newPwd);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "success";
	}

	@RequestMapping("/setnewpwdcfr")
	@ResponseBody
	public String setNewPwdcfr(String accName, String newPwd) {
		try {
			userServer.setNewPwd(accName, newPwd);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "success";
	}

	/**
	 * 描述： 充值页面 创建人： xiaoy 创建时间：2015年2月28日 上午10:43:40 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/recharge")
	public String recharge(HttpSession session, ModelMap map) {
		try {
			Object userAccount = session.getAttribute("name");
			if (userAccount != null) {
				UserTab userTab = userTabDAO.findByUserAcc(userAccount).get(0);
				map.put("user", userTab);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		map.put("title", "充值入口");
		map.put("games", gameTabDAO.findAll());
		return "recharge";
	}

	/**
	 * 描述： 密码找回 创建人： xiaoy 创建时间：2015年2月28日 上午10:44:27 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/passwordback")
	public String passwordback(ModelMap map) {
		map.put("title", "密码找回");
		return "passwordback";
	}

	/**
	 * 描述： 客服中心 创建人： xiaoy 创建时间：2015年2月28日 上午10:45:01 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/customerservicecenter")
	public String customerservicecenter(HttpSession session, ModelMap map,
			Short pageIndex, String showPage, String queryKey) {
		try {
			pageIndex = pageIndex == null ? 0 : pageIndex;
			queryKey = "".equals(queryKey) ? null : queryKey;
			UserTab userTab = new UserTab();
			Object accName = session.getAttribute("name");
			if (accName != null) {
				userTab = userTabDAO.findByUserAcc(accName).get(0);
			}
			// 用户留言单
			if ("question".equals(showPage)) {
				Questionandanswer example = new Questionandanswer();
				if (accName != null) {
					map.put("contact", userTab.getPhone());
				}
				example.setQuestionName(queryKey);
				List<Questionandanswer> questionTotal = questionandanswerDAO
						.findByExample(example);
				List<Questionandanswer> questionandanswers = new ArrayList<Questionandanswer>();
				int left = pageIndex * 10;
				int right = pageIndex * 10 + 10 < questionTotal.size() ? pageIndex * 10 + 10
						: questionTotal.size();
				if (left <= right) {
					questionandanswers = questionTotal.subList(left, right);
				}
				map.put("questions", questionandanswers);
				map.put("total", questionTotal.size());
				map.put("pageNo", pageIndex);
				map.put("maxPageNo", Math.ceil(questionTotal.size() / 10.0));
				map.put("complaintQueryText", queryKey);
			}

			// 实名申诉单
			if ("complaintRealName".equals(showPage)) {

				Complaints exampleTrueName = new Complaints();
				exampleTrueName.setType(Code.trueNameCheck);
				exampleTrueName.setUserAcc(queryKey);
				List<Complaints> complaintsTotal = complaintsDAO
						.findByExample(exampleTrueName);
				List<Complaints> complaintsTrueName = new ArrayList<Complaints>();
				int left = pageIndex * 10;
				int right = pageIndex * 10 + 10 < complaintsTotal.size() ? pageIndex * 10 + 10
						: complaintsTotal.size();
				if (left < right) {
					complaintsTrueName = complaintsTotal.subList(left, right);
				}

				map.put("complaintsTrueName", complaintsTrueName);
				map.put("totalComplaintsTrueName", complaintsTotal.size());
				map.put("pageNoComplaintsTrueName", pageIndex);
				map.put("maxPageNoComplaintsTrueName",
						Math.ceil(complaintsTotal.size() / 10.0));
				map.put("complaintRealNameQueryText", queryKey);
			}

			// 匿名申诉单
			if ("complaintNormal".equals(showPage)) {
				Complaints exampleNormal = new Complaints();
				exampleNormal.setType(Code.trueNameNoCheck);
				exampleNormal.setUserAcc(queryKey);
				List<Complaints> complaintsNormalTotal = complaintsDAO
						.findByExample(exampleNormal);
				List<Complaints> complaintsNormal = new ArrayList<Complaints>();
				int left = pageIndex * 10;
				int right = pageIndex * 10 + 10 < complaintsNormalTotal.size() ? pageIndex * 10 + 10
						: complaintsNormalTotal.size();
				if (left < right) {
					complaintsNormal = complaintsNormalTotal.subList(left,
							right);
				}

				map.put("complaintsNormal", complaintsNormal);
				map.put("totalComplaintsNormal", complaintsNormalTotal.size());
				map.put("pageNoComplaintsNormal", pageIndex);
				map.put("maxPageNoComplaintsNormal",
						Math.ceil(complaintsNormalTotal.size() / 10.0));
				map.put("complaintNormalQueryText", queryKey);
			}
			// 用户权限级别
			map.put("adminLvl",
					userTab.getAdminLvl() == null ? 0 : userTab.getAdminLvl());
			if ("question".equals(showPage)) {
				map.put("showPage", "question");
			}
			if ("complaintRealName".equals(showPage)) {
				map.put("showPage", "complaintRealName");
			}
			if ("complaintNormal".equals(showPage)) {
				map.put("showPage", "complaintNormal");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		map.put("title", "客服中心");
		return "customerservicecenter";
	}

	@RequestMapping(value = "/checkuser", produces = "application/json")
	@ResponseBody
	public Root checkuser(String useraccount) {
		Root root = new Root();
		ArrayList<UserTab> userTabs = new ArrayList<>();
		try {
			userTabs = userServer.checkuser(useraccount);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (userTabs.size() > 0) {
			root.setCode(Code.OK);
			PasswordBack back = new PasswordBack();
			back.setEmail(userTabs.get(0).getMail());
			back.setQuestion1(userTabs.get(0).getQuestion1());
			back.setQuestion2(userTabs.get(0).getQuestion2());
			back.setQuestion3(userTabs.get(0).getQuestion3());
			back.setPhone(userTabs.get(0).getPhone());
			root.setObject(back);
			return root;
		} else {
			root.setCode(Code.Error);
			return root;
		}
	}

	/**
	 * 描述： 校验密保答案 创建人： xiaoy 创建时间：2015年3月2日 上午11:32:18 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/checkanswer")
	@ResponseBody
	public String checkAnswer(PasswordBack back) {
		String flag = null;
		try {
			flag = userServer.checkAnswer(back);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return flag;
	}

	/**
	 * 描述： 发送密码找回邮件 创建人： xiaoy 创建时间：2015年3月3日 上午11:30:26 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/passwordBackByEmail")
	@ResponseBody
	public String passwordBackByEmail(String userAccount, String email) {
		try {
			String uuid = UUID.randomUUID().toString();
			EmailUtil eUtil = new EmailUtil();
			eUtil.sendEmail(serverinfoDAO, email, "乐控科技账号密码找回邮件", uuid,
					"请复制您的验证码");
			userServer.passwordBackByEmail(userAccount, uuid);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "success";
	}

	@RequestMapping("/checkEmailCode")
	@ResponseBody
	public String checkEmailCode(String userAccount, String emailCode) {
		return userServer.checkEmailCode(userAccount, emailCode);
	}

	@RequestMapping(value = "/uploadAvatar")
	@ResponseBody
	public String uploadAvatar(HttpServletRequest request, HttpSession session)
			throws Exception {
		try {
			String accountName = (String) session.getAttribute("name");
			UserTab userTab = userTabDAO.findByUserAcc(accountName).get(0);
			String path = request.getSession().getServletContext()
					.getRealPath("");
			String dirPath = path + File.separator + "avatar";
			CommonsMultipartResolver resolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (resolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null && !"".equals(file.getOriginalFilename())) {
						String uuid = UUID.randomUUID().toString();
						if (file.getOriginalFilename().split("\\.").length < 1) {
							return "errorType";
						}
						if (!"jpg".equals(file.getOriginalFilename().split(
								"\\.")[1])
								&& !"jpeg".equals(file.getOriginalFilename()
										.split("\\.")[1])
								&& !"png".equals(file.getOriginalFilename()
										.split("\\.")[1])
								&& !"gif".equals(file.getOriginalFilename()
										.split("\\.")[1])) {
							return "errorType";
						}
						if (file.getSize() > 2048000) {
							return "errorSize";
						}
						String suffix = file.getOriginalFilename().split("\\.")[1];
						String filePath = dirPath + File.separator + uuid + "."
								+ suffix;
						file.transferTo(new File(filePath));
						if (userTab.getAvatar() != null
								&& userTab.getAvatar() != "") {
							File oldAvatar = new File(dirPath + File.separator
									+ userTab.getAvatar());
							oldAvatar.delete();
						}
						userTab.setAvatar(uuid + "." + suffix);
					}
				}
			}
			userTabDAO.attachDirty(userTab);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "success";
	}

	@RequestMapping("/news")
	public String news(Short newsType, ModelMap map, Short pageIndex) {
		try {
			Productsnews exemple = new Productsnews();
			exemple.setInfoType(newsType);
			List<Productsnews> newsTotal = productsnewsDAO
					.findByExample(exemple);
			List<Productsnews> news = newsTotal
					.subList(pageIndex * 25, pageIndex * 25 + 25 < newsTotal
							.size() ? pageIndex * 25 + 25 : newsTotal.size());
			map.put("total", newsTotal.size());
			map.put("pageNo", pageIndex);
			map.put("maxPageNo", newsTotal.size() / 25 + 1);
			map.put("newses", news);
			map.put("newsType", newsType);
			if (newsType == 1) {
				map.put("title", "游戏信息");
			}
			if (newsType == 2) {
				map.put("title", "公司动态");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "news";
	}

	@RequestMapping("/newsDetail")
	public String newsDetail(Integer id, ModelMap map) {
		try {
			Productsnews productsnews = productsnewsDAO.findById(id);
			map.put("newsDetail", productsnews);
			if (productsnews.getInfoType() == 1) {
				map.put("title", "游戏信息");
			}
			if (productsnews.getInfoType() == 2) {
				map.put("title", "公司动态");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "newsDetail";
	}

	/**
	 * 描述： 新增留言 创建人： xiaoy 创建时间：2015年3月9日 下午12:00:08 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/addQuestion")
	@ResponseBody
	public String addQuestion(String content, HttpSession session,
			String contact) {
		try {
			Object accName = session.getAttribute("name");
			Questionandanswer questionandanswer = new Questionandanswer();
			questionandanswer.setQuestion(content);
			questionandanswer.setContact(contact);
			if (accName != null) {
				UserTab userTab = userTabDAO.findByUserAcc(accName).get(0);
				questionandanswer.setUserId(userTab.getUserId());
				String questionName = (String) (userTab.getNickName() == null ? accName
						: userTab.getNickName());
				questionandanswer.setQuestionName(questionName);
			}
			if (accName == null) {
				questionandanswer.setQuestionName("游客");
			}
			questionandanswerDAO.save(questionandanswer);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "1";
	}

	/**
	 * 描述： 获取回复内容 创建人： xiaoy 创建时间：2015年3月9日 下午1:51:48 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/getReplyContent")
	@ResponseBody
	public String getReplyContent(Integer id, HttpServletResponse response) {
		Questionandanswer questionandanswer = new Questionandanswer();
		try {
			questionandanswer = questionandanswerDAO.findById(id);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return questionandanswer.getAnswer();
	}

	@RequestMapping("/addReply")
	@ResponseBody
	public String addReply(HttpSession session, String content, Integer id,
			String typeFlag) {
		try {
			String accName = session.getAttribute("name").toString();
			if ("question".equals(typeFlag)) {
				Questionandanswer questionandanswer = questionandanswerDAO
						.findById(id);
				questionandanswer.setAnswerName(accName);
				questionandanswer.setAnswer(content);
				questionandanswer.setAnswerDate(new Timestamp(new Date().getTime()));
				questionandanswerDAO.attachDirty(questionandanswer);
				SendSms sendSms = new SendSms();
				Serverinfo serverInfo = serverinfoDAO.findById((short) 1);
				sendSms.sendSms(questionandanswer.getContact(),
						serverInfo.getSmsAccount(), serverInfo.getSmsPassword(),
						serverInfo.getSmsUrl(),"replay");
			}
			if ("complaint".equals(typeFlag)) {
				Complaints complaints = complaintsDAO.findById(id);
				complaints.setAnswer(content);
				complaints.setAnswerName(accName);
				complaintsDAO.attachDirty(complaints);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "1";
	}

	@RequestMapping("/delQuestion")
	@ResponseBody
	public String delQuestion(Integer id) {
		try {
			Questionandanswer questionandanswer = questionandanswerDAO
					.findById(id);
			questionandanswerDAO.delete(questionandanswer);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "1";
	}

	/**
	 * 描述： 通过身份证信息查找用户 创建人： xiaoy 创建时间：2015年3月10日 上午10:59:01 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/realNameInfoSub")
	@ResponseBody
	public String realNameInfoSub(String realName, String idCard) {
		int flag = 0;
		try {
			UserTab userTab = new UserTab();
			userTab.setTrueName(realName);
			userTab.setIdNumber(idCard);
			flag = userTabDAO.findByExample(userTab).size();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (flag > 0) {
			return "success";
		}
		return "error";
	}

	@RequestMapping("/sendComplaint")
	@ResponseBody
	public String realNameSuccessSub(String userAccount,
			String realNameContact, String realName, String idCard,
			Short flagTrueNameCheck, String normalComplaintInfo) {
		try {
			Complaints complaints = new Complaints();
			complaints.setUserAcc(userAccount);
			complaints.setContact(realNameContact);
			complaints.setTrueName(realName);
			complaints.setIdNumber(idCard);
			complaints.setType(flagTrueNameCheck);
			complaints.setComplaintInfo(normalComplaintInfo);
			complaintsDAO.save(complaints);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	@RequestMapping("/delComplaint")
	@ResponseBody
	public String delComplaint(Integer id) {
		try {
			Complaints complaints = complaintsDAO.findById(id);
			complaintsDAO.delete(complaints);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	@RequestMapping("/myjsp")
	public String myJsp() {
		return "MyJsp";
	}

	/**
	 * 描述： 手机注册校验 创建人： xiaoy 创建时间：2015年3月13日 下午2:54:13 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/regcheckphone")
	@ResponseBody
	public Integer regcheckphone(String phone) {
		try {
			if (userTabDAO.findByUserAcc(phone).size() > 0) {
				return -1;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return 1;
	}

	/**
	 * 描述： 发送手机验证码 创建人： xiaoy 创建时间：2015年3月13日 下午3:13:42 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/regsmscode")
	@ResponseBody
	public String regsmscode(String phone, HttpSession session, Integer type) {
		try {
			SendSms sendSms = new SendSms();
			Serverinfo serverInfo = serverinfoDAO.findById((short) 1);
			Map<String, String> result = sendSms.sendSms(phone,
					serverInfo.getSmsAccount(), serverInfo.getSmsPassword(),
					serverInfo.getSmsUrl(),"sms");
			String code = result.get("code").toString();
			if ("4085".equals(code)) {
				return "4085";
			}
			if (type == 1) {
				session.setAttribute("phoneRegisterCode",
						result.get("mobileCode"));
			}
			if (type == 2) {
				session.setAttribute("secretPhone", result.get("mobileCode"));
			}
			if (type == 3) {
				session.setAttribute("pwdPhoneBack", result.get("mobileCode"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "success";
	}

	/**
	 * 描述： 校验手机验证码 创建人： xiaoy 创建时间：2015年3月13日 下午4:09:29 修改备注：
	 * 
	 * @version
	 */
	@RequestMapping("/checksmscode")
	@ResponseBody
	public Integer checkSmsCode(String phone, String code, String type,
			HttpSession session) {
		try {
			String serverCode = null;
			if ("regist".equals(type)) {
				serverCode = session.getAttribute("phoneRegisterCode")
						.toString();
			}
			if ("secretPhone".equals(type)) {
				serverCode = session.getAttribute("secretPhone").toString();
			}
			if ("pwdPhoneBack".equals(type)) {
				serverCode = session.getAttribute("pwdPhoneBack").toString();
			}
			if (code.equals(serverCode)) {
				return 1;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return -1;
	}

	@RequestMapping("/setSecretPhoneCfr")
	@ResponseBody
	public String setSecretPhoneCfr(String phone, HttpSession session) {
		try {
			UserTab userTab = userTabDAO.findByUserAcc(
					session.getAttribute("name")).get(0);
			userTab.setPhone(phone);
			userTabDAO.attachDirty(userTab);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	@RequestMapping("/setSecretEmailCfr")
	@ResponseBody
	public String setSecretEmailCfr(String mail, HttpSession session) {
		try {
			UserTab userTab = userTabDAO.findByUserAcc(
					session.getAttribute("name")).get(0);
			userTab.setMail(mail);
			userTabDAO.attachDirty(userTab);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}

	@RequestMapping("/getServerByGame")
	@ResponseBody
	public Object getServerByGame(Integer gameId) {
		List<ServerTab> servers = new ArrayList<>();
		try {
			ServerTab exmple = new ServerTab();
			exmple.setGameId(gameId);
			servers = serverTabDAO.findByExample(exmple);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return servers;
	}
	
	@RequestMapping("/getRolesByServer")
	@ResponseBody
	public Object getRolesByServer(Integer serverId) {
		List<RoleTab> roles = new ArrayList<>();
		try {
			RoleTab exmple=new RoleTab();
			exmple.setServerId(serverId);
			roles = roleTabDAO.findByExample(exmple);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return roles;
	}
}
